<?php
require_once('DbHelper.php');

$nodeId = $_POST['node'];
$nodeType = $_POST['type'];
if (!isset($nodeId) && !(isset($nodeType)))
{
	die('Must supply a node reference and type!');
}

$connection = DbHelper::createConnection();
$children = array();
if ($nodeType == 'root') 
{
	$result = mysql_query('SELECT * FROM site');
	while($site = mysql_fetch_object($result))
	{
		// create node array from site properties
		// add the node array to the array of children
		$children[] = array(
			'id'=>$site->id,
			'text'=>$site->name,
			'url'=>$site->url,
			'type'=>'site'
		);
	}	
}
else
{
	// build the query based on the node's type. Sites are a special condition
	// as their node ID won't correspond with anything that's in the structure
	// table. Rather we need to look up based on the site id and where the nodes
	// have no parents. For everything else we can just assume that the node ID
	// will be the parent of some child nodes.
	$query = 'SELECT * FROM site_structure WHERE parent_id = ';
	if ($nodeType == 'site') 
	{
		$query .= '0 AND site_id = ' . $nodeId;
	}
	else
	{
		$query .= $nodeId;
	}
	$query .= ' ORDER BY display_order';
	
	$result = mysql_query($query) or die($query . ' ' . mysql_error);
	while($item = mysql_fetch_object($result))
	{
		// create node array from site properties
		// add the node array to the array of children
		$children[] = array(
			'id'=>$item->id,
			'text'=>$item->label,
			'leaf'=>!(bool)$item->has_children,
			'type'=>($item->has_children) ? 'folder' : 'page',
			'pageId'=>$item->page_id,
			'siteId'=>$item->site_id,
			'displayOrder'=>$item->display_order
		);
	}
}

DbHelper::closeConnection($connection);

// encode the array of object in JSON format and return
echo json_encode($children);
?>
